import React, { useState, useEffect } from 'react';
import { is_empty, useCmd, WaitUmd, MainView, useHigh, loc } from 'sui';
import { load_plc } from '../cmd/load';
import { build_plc } from '../cmd/tree';
import { ValueView } from '../view/value';
import { IterView } from '../iter/view';
import { PlcView } from '../plc/view';

const PlcTree = ({ sideopen, setEvent }) => {
    const [main, setMain] = useState();
    const [mod, setMod] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        load_plc(null, v => setMain(v));
    }, []);

    const Empty = () => (
        <div className="bg-title flex justify-center text-lg text-gray-600 ml-4">
            <div className="mt-3 mb-4">{loc("mg_271")}</div>
        </div>
    );

    const getView = () => {
        const haction = (v) => {
            build_plc(main, v, setMain);
        };

        if (!mod || is_empty(main)) {
            return <Empty/>;
        }

        let f = null;

        for (let i = 0; i < main.length; i++) {
            const plc = main[i];
            if (plc.uid === mod) {
                f = plc;
                break;
            }

            if (is_empty(plc.sub)) {
                continue;
            }

            f = plc.sub.find(t => t.uid === mod);
            if (f) {
                break;
            }
        }

        if (!f) {
            return <Empty/>;
        }

        const tp = f.tp;

        if (tp === "timer") {
            return <ValueView mod={mod} reload={v => haction(v)}/>;
        }

        if (tp === "plc") {
            return <IterView mod={mod} reload={v => haction(v)} setEvent={setEvent}/>;
        }

        return <Empty/>;
    };

    return (
        <MainView>
            <div className="inline-flex">
                <PlcView high={high} mod={mod} setMod={setMod} main={main} hcmd={v => build_plc(main, v, setMain)}/>
                <div className="w-3/4">
                    {getView()}
                </div>
            </div>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {PlcTree};
